<?php
/**
 * Created by PhpStorm.
 * User: hasee
 * Date: 2016/10/26
 * Time: 19:24
 */
namespace app\components\behaviors;
use app\models\Log;
use Yii;
use yii\base\Behavior;
use yii\base\ErrorException;
use yii\bootstrap\Html;
use yii\db\ActiveRecord;
//use yii\log\FileTarget;
class LogBehavior extends Behavior{
	public $createTemplate = "添加{{tableName}}:{{attributeValue}}";
	public $updateTemplate = "修改{{tableName}}:{{attributeValue}}";
	public $deleteTemplate = "删除{{tableName}}:{{attributeValue}}";
    public $tableName;
    public $attributeValue;
	public function events(){
		return [
            ActiveRecord::EVENT_AFTER_INSERT => 'create',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'update',
            ActiveRecord::EVENT_AFTER_DELETE => 'delete',
		];
	}

    //生成日志
    protected function genLog($name)
    {
        //获取模板
        $templateName = $name."Template";
        $template = $this->$templateName;
        //替换模板标签
        $template = str_replace('{{tableName}}',$this->tableName,$template);
        $template = str_replace('{{attributeValue}}',$this->owner->{$this->attributeValue},$template);
        return $template;
    }
    //保存日志
    protected function saveLog($content)
    {
        //实例化日志类
        $log = new Log();
        //属性赋值
        $log->rz_shijian = $content;
        //保存
        if (!$log->save())
        {
            throw new ErrorException("保存日志失败!".Html::errorSummary($log));
        }
    }
    protected function handle($name)
    {
        //生成日志内容
        $content= $this->genLog($name);
        if ($name == 'update') {
            $msg = $this->genUpdateContent($name);
            $content .= $msg;
        }
        //保存日志
        $this->saveLog($content);

    }


    public function __call($name, $params)
    {
        if (in_array($name,['create','update','delete']))
        {
            return $this->handle($name);
        }
        parent::__call($name, $params);
    }

    /**
     * @param $name
     * @return string
     */
    protected function genUpdateContent()
    {
        $model = $this->owner;
        /**@var $model ActiveRecord */
        $dirties = $model->getDirtyAttributes();
        $msg = "--修改内容[";
        $name = "";
        foreach ($dirties as $key => $value) {
            $name = $model->getAttributeLabel($key);
            $msg .= $name . ":" . $value . ",";
        }
        $msg .= "]";
        return $msg;
    }

}